<template>
  <div v-if="mixinState.mSelectMode === 'one' && type === 'image'">
    <Divider plain orientation="left">图片</Divider>
    <div
      :style="`background-image:url('${
        state.imgUrl ? state.imgUrl : canvasEditor.canvas.getActiveObjects()[0].get('imgUrl')
      }');`"
      class="attr-item box"
    >
      <template class="boxitem">
        <Input
          v-model="state.imgUrl"
          :placeholder="state.placeholder"
          clearable
          @change="(e) => urlRepleace(e)"
          class="mb-2"
        />
        <Button @click="repleace" type="primary" long>上传本地图片</Button>
      </template>
    </div>
  </div>
</template>

<script setup name="ReplaceImg">
import useSelect from '@/hooks/select';
import { getImgStr, selectFiles, insertImgFile } from '@/utils/utils';
const state = reactive({
  imgUrl: '',
  placeholder: '请输入图片url地址',
});

const update = getCurrentInstance();
const event = inject('event');
const { mixinState, canvasEditor } = useSelect();
const type = ref('');

// 替换图片
const repleace = async () => {
  const activeObject = canvasEditor.canvas.getActiveObjects()[0];
  if (activeObject && activeObject.type === 'image') {
    const [file] = await selectFiles({ accept: 'image/*', multiple: false }); // 图片
    const fileStr = await getImgStr(file); // 转字符串
    const imgEl = await insertImgFile(fileStr); // 字符串转El
    const width = imgEl.width;
    const height = imgEl.height;
    const scaleX = activeObject.get('scaleX');
    const scaleY = activeObject.get('scaleY');
    activeObject.setSrc(
      imgEl.src,
      () => {
        activeObject.set('scaleX', (width * scaleX) / imgEl.width);
        activeObject.set('scaleY', (height * scaleY) / imgEl.height);
        activeObject.set('imgUrl', fileStr);
        canvasEditor.canvas.renderAll();
      },
      { crossOrigin: 'anonymous' }
    );
    imgEl.remove();
    state.imgUrl = fileStr;
  }
};

const urlRepleace = (e) => {
  const activeObject = canvasEditor.canvas.getActiveObjects()[0];
  if (activeObject && activeObject.type === 'image' && state?.imgUrl && state?.imgUrl) {
    let imgUrl = e.target.value;
    let image = new Image();
    image.src = imgUrl + '?v=' + Math.random(); // 处理缓存
    image.crossOrigin = '*'; // 支持跨域图片
    image.onload = async () => {
      // let canvas = document.createElement('canvas');
      // canvas.width = image.width;
      // canvas.height = image.height;
      // let ctx = canvas.getContext('2d');
      // ctx.drawImage(image, 0, 0, image.width, image.height);
      // let fileStr = canvas.toDataURL('image/png');
      // const imgEl = await insertImgFile(fileStr); // 字符串转El
      const width = image.width;
      const height = image.height;
      const scaleX = activeObject.get('scaleX');
      const scaleY = activeObject.get('scaleY');

      activeObject.setSrc(
        image.src,
        () => {
          activeObject.set('scaleX', (width * scaleX) / image.width);
          activeObject.set('scaleY', (height * scaleY) / image.height);
          activeObject.set('imgUrl', image.src);
          canvasEditor.canvas.renderAll();
        },
        { crossOrigin: 'anonymous' }
      );
      // imgEl.remove();
    };
  }
};

const init = () => {
  const activeObject = canvasEditor.canvas.getActiveObjects()[0];
  if (activeObject) {
    state.imgUrl = activeObject.imgUrl ? activeObject.imgUrl : activeObject.src;
    type.value = activeObject.type;
    update?.proxy?.$forceUpdate();
  }
};

onMounted(() => {
  event.on('selectOne', init);
});

onBeforeUnmount(() => {
  event.off('selectOne', init);
});
</script>
<style scoped>
.box {
  position: relative;
  height: 120px !important;
  width: 90%;
  margin: 5%;
  background-size: contain !important;
  background-repeat: no-repeat !important;
  background-position: center !important;
}
.boxitem {
  display: none;
}
.box:hover {
  background-color: rgba(85, 85, 85, 0.6);
}
.box:hover .boxitem {
  display: flex;
  width: 100%;
  height: 80%;
  flex-direction: column;
  justify-content: flex-end;
}
</style>
